﻿
@model Product.Mvc.Models.PlanModel
@{    ViewData["Title"] = "新增生产计划";}

<!-- 页面样式 -->
<style>
    .form-container {
        padding: 20px;
        background-color: #f8f9fa;
        border-radius: 5px;
        margin-bottom: 20px;
    }
    .btn-group {
        margin-bottom: 15px;
    }
    .table-container {
        background-color: white;
        border-radius: 5px;
        padding: 15px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    .total-count {
        margin-top: 10px;
        text-align: right;
        font-weight: bold;
    }
</style>

<div class="container mt-4">
    <div class="card">
        <div class="card-header bg-primary text-white">
            新增生产计划
        </div>
        <div class="card-body">
            <form>
                <div class="form-container">
                    <h5>基础信息</h5>
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label for="planNo" class="form-label">计划编号</label>
                            <input type="text" id="planNo" name="planNo" value="@Model?.Plan_Number" class="form-control" placeholder="PLAN-20250829-190221">
                        </div>
                        <div class="col-md-4">
                            <label for="planTitle" class="form-label">计划名称</label>
                            <input type="text" id="planTitle" name="planTitle" value="@Model?.Plan_Name" class="form-control" placeholder="输入计划名称">
                        </div>
                        <div class="col-md-4">
                            <label for="sourceType" class="form-label">来源类型</label>
                            <select id="sourceType" name="sourceType" class="form-select">
                                <option value="">请选择来源类型</option>
                  @*               <option value="销售订单" @(Model?.Source_Type == "销售订单" ? "selected" : "")>销售订单</option>
                                <option value="预测订单" @(Model?.Source_Type == "预测订单" ? "selected" : "")>预测订单</option>
                                <option value="计划订单" @(Model?.Source_Type == "计划订单" ? "selected" : "")>计划订单</option>
                                <option value="不绑定" @(Model?.Source_Type == "不绑定" ? "selected" : "")>不绑定</option> *@
                            </select>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label for="salesOrder" class="form-label">订单编号</label>
                            <div class="input-group">
                                <input type="text" id="salesOrder" name="salesOrder" value="@Model?.Order_Number" class="form-control" placeholder="选择订单编号" readonly>
                                <div class="input-group-append">
                                    <button type="button" id="btnSelectSalesOrder" class="btn btn-primary">选择</button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label for="planStartTime" class="form-label">计划工时时间</label>
                            <input type="datetime-local" id="planStartTime" name="planStartTime" value="2025-08-29T11:02" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label for="planEndTime" class="form-label">计划完工时间</label>
                            <input type="datetime-local" id="planEndTime" name="planEndTime" value="2025-08-30T11:02" class="form-control">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label for="requirementDate" class="form-label">需求日期</label>
                            <input type="datetime-local" id="requirementDate" name="requirementDate" value="2025-08-30T11:02" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label for="status" class="form-label">状态</label>
                            <select id="status" name="status" class="form-select">
                                <option value="">请选择状态</option>
                                <option value="未开始" selected>未开始</option>
                                <option value="进行中">进行中</option>
                                <option value="已完成">已完成</option>
                                <option value="已取消">已取消</option>
                            </select>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <label for="remark" class="form-label">备注</label>
                            <textarea id="remark" name="remark" rows="3" class="form-control" placeholder="输入备注">@Model?.Notes</textarea>
                        </div>
                    </div>
                </div>

                <div class="table-container">
                    <h5>生产物品</h5>
                    <div class="btn-group">
                        <button type="button" id="btnAddItem" class="btn btn-primary">添加</button>
                        <button type="button" id="btnRemoveItem" class="btn btn-danger">移除</button>
                    </div>
                    
                    <table id="itemTable" class="table table-bordered mt-3">
                        <thead class="thead-light">
                            <tr>
                                <th><input type="checkbox" id="selectAll" class="form-check-input"></th>
                                <th>序号</th>
                                <th>物品名称</th>
                                <th>规格型号</th>
                                <th>单位</th>
                                <th>物品类别</th>
                                <th>物品分类</th>
                                <th>品牌</th>
                                <th>数量</th>
                                <th>计划日期</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            @if (Model != null && Model.ProductItems != null && Model.ProductItems.Count > 0)
                            {
                                int index = 1;
                                foreach (var item in Model.ProductItems)
                                {
                                    <tr>
                                        <td><input type="checkbox" name="selectItem" class="form-check-input"></td>
                                        <td>@index</td>
                                        <td><input type="text" name="itemName" value="@item.ItemName" class="form-control" style="width: 100%;"></td>
                                        <td><input type="text" name="specModel" value="@item.Model" class="form-control" style="width: 100%;"></td>
                                        <td><input type="text" name="unit" value="@item.Unit" class="form-control" style="width: 100%;"></td>
                                        <td><input type="text" name="itemCategory" value="@item.Category" class="form-control" style="width: 100%;"></td>
                                        <td><input type="text" name="itemType" value="电子产品" class="form-control" style="width: 100%;"></td>
                                        <td><input type="text" name="brand" value="@item.Brand" class="form-control" style="width: 100%;"></td>
                                        <td><input type="number" name="quantity" value="@item.Quantity" class="form-control" style="width: 100%;" min="0" step="1"></td>
                                        <td><input type="date" name="detailDate" class="form-control detail-date" style="width: 100%;"></td>
                                        <td>
                                            <button type="button" class="btn btn-danger btn-sm remove-item">移除</button>
                                        </td>
                                    </tr>
                                    index++;
                                }
                            }
                            else
                            {
                                <tr>
                                    <td colspan="11" style="text-align: center;">暂无数据，请点击添加按钮</td>
                                </tr>
                            }
                        </tbody>
                    </table>
                    
                    <div class="total-count">总计：0</div>
                </div>

                <!-- 提交按钮 -->
                <div class="mt-4 text-center">
                    <button type="submit" class="btn btn-primary">提交</button>
                    <button type="button" id="btnCancel" class="btn btn-secondary">取消</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- JavaScript代码已移至页面底部的@section Scripts部分 -->

<!-- 销售订单选择弹出框 -->
<div id="salesOrderModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="salesOrderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="salesOrderModalLabel">选择销售订单</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-3">
                        <input type="text" id="searchOrderNo" class="form-control" placeholder="输入销售单号/主题">
                    </div>
                    <div class="col-md-3">
                        <input type="text" id="searchCustomerName" class="form-control" placeholder="输入客户名称">
                    </div>
                    <div class="col-md-3">
                        <input type="date" id="searchOrderDate" class="form-control">
                    </div>
                    <div class="col-md-3">
                        <select id="searchOrderStatus" class="form-control">
                            <option value="">请选择销售状态</option>
                            <option value="未完成">未完成</option>
                            <option value="已完成">已完成</option>
                        </select>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-12 text-right">
                        <button type="button" id="btnSearchOrder" class="btn btn-primary mr-2">查询</button>
                        <button type="button" id="btnResetOrder" class="btn btn-secondary">重置</button>
                    </div>
                </div>
                <div class="table-responsive">
                    <table id="orderTable" class="table table-bordered">
                        <thead>
                            <tr>
                                <th><input type="checkbox" id="selectAllOrders"></th>
                                <th>序号</th>
                                <th>销售单号</th>
                                <th>销售订单主题</th>
                                <th>客户名称</th>
                                <th>销售日期</th>
                                <th>采购状态</th>
                                <th>物品概要</th>
                            </tr>
                        </thead>
                        <tbody id="orderTableBody">
                            <!-- 模拟数据将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>
                <div class="row mt-3">
                    <div class="col-md-6">
                        共 <span id="totalOrderCount">0</span> 项数据
                    </div>
                    <div class="col-md-6 text-right">
                        <nav aria-label="Page navigation">
                            <ul class="pagination" id="pagination">
                                <!-- 分页将通过JavaScript动态生成 -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" id="btnCancelOrderSelect" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" id="btnConfirmOrderSelect" class="btn btn-primary">确定</button>
            </div>
        </div>
    </div>
</div>
        
@section Scripts {
    <script>
        // 等待页面加载完成
        $(document).ready(function() {
            // 销售订单弹出框相关功能
            let selectedOrderId = null;
            let selectedOrderNumber = null;
            let currentPage = 1;
            const pageSize = 5;
            
            // 模拟销售订单数据
            const mockOrders = [
                { id: 1, orderNo: 'XSDH001', title: '华为P50手机购买订单', customerName: '逻辑不通有限公司', orderDate: '2024-06-26', status: '未完成', itemsSummary: '产品0515 等1项' },
                { id: 2, orderNo: 'XSDH002', title: '高精度工业级金属切削机床销售单', customerName: '笑笑笑企业', orderDate: '2024-06-26', status: '未完成', itemsSummary: '产品0215: 60\n产品0232: 10\n产品: 10' },
                { id: 3, orderNo: 'XSDH004', title: '超级好康限时促销单', customerName: '抢购狂魔企业', orderDate: '2024-06-25', status: '未完成', itemsSummary: '各种产品组合' },
                { id: 4, orderNo: 'XSDH005', title: '狂欢节特别优惠销售单', customerName: '欢乐购物主义', orderDate: '2024-06-24', status: '已完成', itemsSummary: '特价商品' },
                { id: 5, orderNo: 'XSDH003', title: '疯狂大减价特惠销售单', customerName: '开心购物狂', orderDate: '2024-06-25', status: '已完成', itemsSummary: '多种商品组合 等1项' },
                { id: 6, orderNo: 'XSDH006', title: '企业年度采购订单', customerName: '未来科技公司', orderDate: '2024-06-23', status: '未完成', itemsSummary: '办公设备 等5项' },
                { id: 7, orderNo: 'XSDH007', title: '生产线升级配件订单', customerName: '智能工厂集团', orderDate: '2024-06-22', status: '已完成', itemsSummary: '机械配件 等3项' },
                { id: 8, orderNo: 'XSDH008', title: '研发项目专用设备采购', customerName: '创新研究院', orderDate: '2024-06-21', status: '未完成', itemsSummary: '科研设备 等2项' },
                { id: 9, orderNo: 'XSDH009', title: '季度办公用品补充', customerName: '恒信企业管理', orderDate: '2024-06-20', status: '已完成', itemsSummary: '办公用品 等10项' },
                { id: 10, orderNo: 'XSDH010', title: '新产品发布会物料', customerName: '星耀科技', orderDate: '2024-06-19', status: '未完成', itemsSummary: '宣传物料 等8项' },
                { id: 11, orderNo: 'XSDH011', title: '客户定制化解决方案', customerName: '卓越制造', orderDate: '2024-06-18', status: '未完成', itemsSummary: '定制产品 等4项' },
                { id: 12, orderNo: 'XSDH012', title: '企业福利采购', customerName: '和谐集团', orderDate: '2024-06-17', status: '已完成', itemsSummary: '员工福利 等6项' },
                { id: 13, orderNo: 'XSDH013', title: '节日促销活动物料', customerName: '欢乐购物广场', orderDate: '2024-06-16', status: '未完成', itemsSummary: '促销物料 等7项' },
                { id: 14, orderNo: 'XSDH014', title: '年度维护保养服务', customerName: '远大机械', orderDate: '2024-06-15', status: '已完成', itemsSummary: '维保服务 等2项' },
                { id: 15, orderNo: 'XSDH015', title: '紧急采购补充', customerName: '速达物流', orderDate: '2024-06-14', status: '未完成', itemsSummary: '物流设备 等3项' },
                { id: 16, orderNo: 'XSDH016', title: '客户积分兑换礼品', customerName: '忠诚客户计划', orderDate: '2024-06-13', status: '已完成', itemsSummary: '礼品 等5项' },
                { id: 17, orderNo: 'XSDH017', title: '合作伙伴样品订单', customerName: '共赢商贸', orderDate: '2024-06-12', status: '未完成', itemsSummary: '样品 等9项' },
                { id: 18, orderNo: 'XSDH018', title: '展会参展设备', customerName: '环球展览', orderDate: '2024-06-11', status: '已完成', itemsSummary: '展架 等4项' },
                { id: 19, orderNo: 'XSDH019', title: '内部培训设备', customerName: '企业大学', orderDate: '2024-06-10', status: '未完成', itemsSummary: '培训设备 等3项' },
                { id: 20, orderNo: 'XSDH020', title: '客户投诉赔偿', customerName: '满意服务部', orderDate: '2024-06-09', status: '已完成', itemsSummary: '赔偿商品 等2项' },
                { id: 21, orderNo: 'XSDH021', title: '新市场开拓样品', customerName: '国际业务部', orderDate: '2024-06-08', status: '未完成', itemsSummary: '样品 等6项' },
                { id: 22, orderNo: 'XSDH022', title: 'VIP客户专属礼品', customerName: '大客户部', orderDate: '2024-06-07', status: '已完成', itemsSummary: '礼品 等5项' },
                { id: 23, orderNo: 'XSDH023', title: '售后维修配件', customerName: '售后服务中心', orderDate: '2024-06-06', status: '未完成', itemsSummary: '配件 等8项' },
                { id: 24, orderNo: 'XSDH024', title: '市场调研样品', customerName: '市场部', orderDate: '2024-06-05', status: '已完成', itemsSummary: '样品 等3项' },
                { id: 25, orderNo: 'XSDH025', title: '员工内部购买', customerName: '人力资源部', orderDate: '2024-06-04', status: '未完成', itemsSummary: '内部优惠商品 等10项' },
                { id: 26, orderNo: 'XSDH026', title: '供应商合作样品', customerName: '采购部', orderDate: '2024-06-03', status: '已完成', itemsSummary: '合作样品 等7项' },
                { id: 27, orderNo: 'XSDH027', title: '政府招标项目', customerName: '公共事业部', orderDate: '2024-06-02', status: '未完成', itemsSummary: '招标产品 等12项' },
                { id: 28, orderNo: 'XSDH028', title: '教育机构采购', customerName: '教育合作部', orderDate: '2024-06-01', status: '已完成', itemsSummary: '教学设备 等9项' },
                { id: 29, orderNo: 'XSDH029', title: '医疗行业专用设备', customerName: '医疗事业部', orderDate: '2024-05-31', status: '未完成', itemsSummary: '医疗设备 等6项' },
                { id: 30, orderNo: 'XSDH030', title: '金融行业解决方案', customerName: '金融事业部', orderDate: '2024-05-30', status: '已完成', itemsSummary: '金融设备 等8项' },
                { id: 31, orderNo: 'XSDH031', title: '电信运营商采购', customerName: '电信事业部', orderDate: '2024-05-29', status: '未完成', itemsSummary: '通信设备 等15项' },
                { id: 32, orderNo: 'XSDH032', title: '能源行业专用产品', customerName: '能源事业部', orderDate: '2024-05-28', status: '已完成', itemsSummary: '能源设备 等7项' },
                { id: 33, orderNo: 'XSDH033', title: '交通行业解决方案', customerName: '交通事业部', orderDate: '2024-05-27', status: '未完成', itemsSummary: '交通设备 等10项' },
                { id: 34, orderNo: 'XSDH034', title: '建筑行业专用工具', customerName: '建筑事业部', orderDate: '2024-05-26', status: '已完成', itemsSummary: '建筑工具 等8项' },
                { id: 35, orderNo: 'XSDH035', title: '农业现代化设备', customerName: '农业事业部', orderDate: '2024-05-25', status: '未完成', itemsSummary: '农业设备 等6项' },
                { id: 36, orderNo: 'XSDH036', title: '环保行业解决方案', customerName: '环保事业部', orderDate: '2024-05-24', status: '已完成', itemsSummary: '环保设备 等9项' }
            ];
            
            // 渲染订单列表
            function renderOrderTable(orders) {
                const tableBody = $('#orderTableBody');
                tableBody.empty();
                
                // 计算分页
                const totalPages = Math.ceil(orders.length / pageSize);
                const startIndex = (currentPage - 1) * pageSize;
                const endIndex = Math.min(startIndex + pageSize, orders.length);
                const paginatedOrders = orders.slice(startIndex, endIndex);
                
                // 显示总数
                $('#totalOrderCount').text(orders.length);
                
                // 渲染订单行
                if (paginatedOrders.length === 0) {
                    tableBody.append('<tr><td colspan="8" style="text-align: center;">暂无数据</td></tr>');
                } else {
                    paginatedOrders.forEach((order, index) => {
                        const rowNum = startIndex + index + 1;
                        const isSelected = selectedOrderId === order.id;
                        const itemsSummaryHtml = order.itemsSummary.split('\n').join('<br>');
                        
                        const row = `
                            <tr>
                                <td><input type="checkbox" class="order-checkbox" data-id="${order.id}" data-number="${order.orderNo}" ${isSelected ? 'checked' : ''}></td>
                                <td>${rowNum}</td>
                                <td>${order.orderNo}</td>
                                <td>${order.title}</td>
                                <td>${order.customerName}</td>
                                <td>${order.orderDate}</td>
                                <td>${order.status}</td>
                                <td>
                                    <div class="dropdown">
                                        <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton${order.id}" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                            ${itemsSummaryHtml}
                                        </button>
                                        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton${order.id}">
                                            <div class="p-2">${itemsSummaryHtml}</div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        `;
                        tableBody.append(row);
                    });
                }
                
                // 渲染分页
                renderPagination(totalPages);
            }
            
            // 渲染分页控件
            function renderPagination(totalPages) {
                const pagination = $('#pagination');
                pagination.empty();
                
                if (totalPages <= 1) return;
                
                // 上一页
                const prevPage = $('<li>').addClass('page-item');
                const prevLink = $('<a>').addClass('page-link').attr('href', '#').text('上一页');
                if (currentPage === 1) {
                    prevPage.addClass('disabled');
                } else {
                    prevLink.on('click', function(e) {
                        e.preventDefault();
                        currentPage--;
                        searchOrders();
                    });
                }
                prevPage.append(prevLink);
                pagination.append(prevPage);
                
                // 页码按钮
                const maxVisiblePages = 5;
                let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
                let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
                
                if (endPage - startPage + 1 < maxVisiblePages) {
                    startPage = Math.max(1, endPage - maxVisiblePages + 1);
                }
                
                for (let i = startPage; i <= endPage; i++) {
                    const pageItem = $('<li>').addClass('page-item');
                    const pageLink = $('<a>').addClass('page-link').attr('href', '#').text(i);
                    
                    if (i === currentPage) {
                        pageItem.addClass('active');
                    } else {
                        pageLink.on('click', function(e) {
                            e.preventDefault();
                            currentPage = i;
                            searchOrders();
                        });
                    }
                    
                    pageItem.append(pageLink);
                    pagination.append(pageItem);
                }
                
                // 下一页
                const nextPage = $('<li>').addClass('page-item');
                const nextLink = $('<a>').addClass('page-link').attr('href', '#').text('下一页');
                if (currentPage === totalPages) {
                    nextPage.addClass('disabled');
                } else {
                    nextLink.on('click', function(e) {
                        e.preventDefault();
                        currentPage++;
                        searchOrders();
                    });
                }
                nextPage.append(nextLink);
                pagination.append(nextPage);
            }
            
            // 查询订单
            function searchOrders() {
                const orderNo = $('#searchOrderNo').val().toLowerCase();
                const customerName = $('#searchCustomerName').val().toLowerCase();
                const orderDate = $('#searchOrderDate').val();
                const orderStatus = $('#searchOrderStatus').val();
                
                let filteredOrders = mockOrders;
                
                // 按销售单号/主题筛选
                if (orderNo) {
                    filteredOrders = filteredOrders.filter(order => 
                        order.orderNo.toLowerCase().includes(orderNo) || 
                        order.title.toLowerCase().includes(orderNo)
                    );
                }
                
                // 按客户名称筛选
                if (customerName) {
                    filteredOrders = filteredOrders.filter(order => 
                        order.customerName.toLowerCase().includes(customerName)
                    );
                }
                
                // 按销售日期筛选
                if (orderDate) {
                    filteredOrders = filteredOrders.filter(order => 
                        order.orderDate === orderDate
                    );
                }
                
                // 按采购状态筛选
                if (orderStatus) {
                    filteredOrders = filteredOrders.filter(order => 
                        order.status === orderStatus
                    );
                }
                
                renderOrderTable(filteredOrders);
            }
            
            // 重置查询条件
            function resetSearch() {
                $('#searchOrderNo').val('');
                $('#searchCustomerName').val('');
                $('#searchOrderDate').val('');
                $('#searchOrderStatus').val('');
                currentPage = 1;
                searchOrders();
            }
            
            // 选择销售订单按钮点击事件
            $('#btnSelectSalesOrder').on('click', function() {
                currentPage = 1;
                searchOrders();
                $('#salesOrderModal').modal('show');
            });
            
            // 查询按钮点击事件
            $('#btnSearchOrder').on('click', function() {
                currentPage = 1;
                searchOrders();
            });
            
            // 重置按钮点击事件
            $('#btnResetOrder').on('click', resetSearch);
            
            // 全选/取消全选
            $('#selectAllOrders').on('change', function() {
                const isChecked = $(this).prop('checked');
                $('.order-checkbox').prop('checked', isChecked);
                
                if (isChecked && $('.order-checkbox:checked').length > 0) {
                    const firstChecked = $('.order-checkbox:checked').first();
                    selectedOrderId = parseInt(firstChecked.data('id'));
                    selectedOrderNumber = firstChecked.data('number');
                }
            });
            
            // 单选订单
            $(document).on('change', '.order-checkbox', function() {
                const isChecked = $(this).prop('checked');
                
                if (isChecked) {
                    // 取消其他选中
                    $('.order-checkbox').not(this).prop('checked', false);
                    $('#selectAllOrders').prop('checked', false);
                    selectedOrderId = parseInt($(this).data('id'));
                    selectedOrderNumber = $(this).data('number');
                } else {
                    selectedOrderId = null;
                    selectedOrderNumber = null;
                }
            });
            
            // 确认选择订单
            $('#btnConfirmOrderSelect').on('click', function() {
                if (selectedOrderNumber) {
                    $('#salesOrder').val(selectedOrderNumber);
                    $('#salesOrderModal').modal('hide');
                } else {
                    alert('请选择销售订单');
                }
            });
            
            // 取消选择订单
            $('#btnCancelOrderSelect').on('click', function() {
                $('#salesOrderModal').modal('hide');
            });
            
            // 来源类型下拉框变化事件
            $('#sourceType').on('change', function() {
                if ($(this).val() === '不绑定') {
                    $('#salesOrder').val('');
                    $('#salesOrder').prop('readonly', true);
                    $('#btnSelectSalesOrder').prop('disabled', true);
                } else {
                    $('#salesOrder').prop('readonly', false);
                    $('#btnSelectSalesOrder').prop('disabled', false);
                }
            });
            
            // 初始化来源类型状态
            if ($('#sourceType').val() === '不绑定') {
                $('#salesOrder').prop('readonly', true);
                $('#btnSelectSalesOrder').prop('disabled', true);
            }
            
            // 初始化订单数据
            searchOrders();
            // 全选/取消全选
            $('#selectAll').on('change', function() {
                $('tbody input[type="checkbox"]').prop('checked', this.checked);
            });
            
            // 添加物品
            $('#btnAddItem').on('click', function() {
                var index = $('#itemTable tbody tr').length + 1;
                var newRow = `
                    <tr>
                        <td><input type="checkbox" name="selectItem" class="form-check-input"></td>
                        <td>${index}</td>
                        <td><input type="text" name="itemName" placeholder="请输入" class="form-control" style="width: 100%;"></td>
                        <td><input type="text" name="specModel" placeholder="请输入" class="form-control" style="width: 100%;"></td>
                        <td><input type="text" name="unit" placeholder="请输入" class="form-control" style="width: 100%;"></td>
                        <td><input type="text" name="itemCategory" placeholder="请输入" class="form-control" style="width: 100%;"></td>
                        <td><input type="text" name="itemType" placeholder="请输入" class="form-control" style="width: 100%;"></td>
                        <td><input type="text" name="brand" placeholder="请输入" class="form-control" style="width: 100%;"></td>
                        <td><input type="number" name="quantity" placeholder="请输入" class="form-control" style="width: 100%;" min="0" step="1"></td>
                        <td><input type="date" name="detailDate" placeholder="请选择日期" class="form-control detail-date" style="width: 100%;"></td>
                        <td>
                            <button type="button" class="btn btn-danger btn-sm remove-item">移除</button>
                        </td>
                    </tr>
                `;
                
                // 检查是否有提示行
                if ($('#itemTable tbody tr td[colspan="11"]').length > 0) {
                    $('#itemTable tbody').empty();
                }
                
                $('#itemTable tbody').append(newRow);
                
                // 重新计算总计
                calculateTotal();
            });
            
            // 单行移除
            $(document).on('click', '.remove-item', function() {
                $(this).closest('tr').remove();
                // 更新序号
                $('#itemTable tbody tr').each(function(index) {
                    $(this).find('td:eq(1)').text(index + 1);
                });
                // 重新计算总计
                calculateTotal();
                
                // 如果表格为空，显示提示
                if ($('#itemTable tbody tr').length === 0) {
                    $('#itemTable tbody').html('<tr><td colspan="11" style="text-align: center;">暂无数据，请点击添加按钮</td></tr>');
                }
            });
            
            // 移除选中物品
            $('#btnRemoveItem').on('click', function() {
                var checkedItems = $('tbody input[type="checkbox"]:checked');
                if (checkedItems.length === 0) {
                    alert('请选择要移除的物品');
                    return;
                }
                
                if (confirm('确定要移除选中的物品吗？')) {
                    checkedItems.each(function() {
                        $(this).closest('tr').remove();
                    });
                    
                    // 更新序号
                    $('#itemTable tbody tr').each(function(index) {
                        $(this).find('td:eq(1)').text(index + 1);
                    });
                    
                    // 重新计算总计
                    calculateTotal();
                    
                    // 如果表格为空，显示提示
                    if ($('#itemTable tbody tr').length === 0) {
                        $('#itemTable tbody').html('<tr><td colspan="11" style="text-align: center;">暂无数据，请点击添加按钮</td></tr>');
                    }
                }
            });
            
            // 计算总计
            function calculateTotal() {
                var total = 0;
                $('input[name="quantity"]').each(function() {
                    var val = $(this).val();
                    if (val && !isNaN(val)) {
                        total += parseFloat(val);
                    }
                });
                $('.total-count').text('总计：' + total);
            }
            
            // 数量变化时重新计算总计
            $(document).on('input', 'input[name="quantity"]', function() {
                calculateTotal();
            });
            
            // 提交表单
            $('form').on('submit', function(event) {
                event.preventDefault(); // 阻止表单默认提交
                
                // 验证必填项
                var isValid = true;
                var errorMsg = '';
                
                // 检查基础信息
                if (!$('input[name="planTitle"]').val()) {
                    errorMsg += '计划名称不能为空\n';
                    isValid = false;
                }
                if (!$('input[name="planNo"]').val()) {
                    errorMsg += '计划编号不能为空\n';
                    isValid = false;
                }
                if (!$('select[name="sourceType"]').val()) {
                    errorMsg += '来源类型不能为空\n';
                    isValid = false;
                }
                if ($('select[name="sourceType"]').val() !== '不绑定' && !$('input[name="salesOrder"]').val()) {
                    errorMsg += '请选择订单编号\n';
                    isValid = false;
                }
                if (!$('input[name="planStartTime"]').val()) {
                    errorMsg += '计划工时时间不能为空\n';
                    isValid = false;
                }
                if (!$('input[name="planEndTime"]').val()) {
                    errorMsg += '计划完工时间不能为空\n';
                    isValid = false;
                }
                if (!$('input[name="requirementDate"]').val()) {
                    errorMsg += '需求日期不能为空\n';
                    isValid = false;
                }
                if (!$('select[name="status"]').val()) {
                    errorMsg += '状态不能为空\n';
                    isValid = false;
                }
                
                // 检查物品数量
                var hasQuantity = false;
                $('input[name="quantity"]').each(function() {
                    var val = $(this).val();
                    if (val && !isNaN(val) && parseFloat(val) > 0) {
                        hasQuantity = true;
                    }
                });
                
                if (!hasQuantity) {
                    errorMsg += '请至少填写一个有效的数量\n';
                    isValid = false;
                }
                
                if (!isValid) {
                    alert(errorMsg);
                    return false;
                }
                
                // 构造提交数据
                var submitData = {
                    planTitle: $('input[name="planTitle"]').val(),
                    planNo: $('input[name="planNo"]').val(),
                    sourceType: $('select[name="sourceType"]').val(),
                    salesOrder: $('input[name="salesOrder"]').val(),
                    planStartTime: $('input[name="planStartTime"]').val(),
                    planEndTime: $('input[name="planEndTime"]').val(),
                    requirementDate: $('input[name="requirementDate"]').val(),
                    status: $('select[name="status"]').val(),
                    remark: $('textarea[name="remark"]').val(),
                    items: []
                };
                
                // 收集物品信息
                $('#itemTable tbody tr').each(function() {
                    var $tr = $(this);
                    var item = {
                        itemName: $tr.find('td:eq(2)').find('input').val() || $tr.find('td:eq(2)').text(),
                        specModel: $tr.find('td:eq(3)').find('input').val() || $tr.find('td:eq(3)').text(),
                        unit: $tr.find('td:eq(4)').find('input').val() || $tr.find('td:eq(4)').text(),
                        itemCategory: $tr.find('td:eq(5)').find('input').val() || $tr.find('td:eq(5)').text(),
                        itemType: $tr.find('td:eq(6)').find('input').val() || $tr.find('td:eq(6)').text(),
                        brand: $tr.find('td:eq(7)').find('input').val() || $tr.find('td:eq(7)').text(),
                        quantity: $tr.find('td:eq(8) input').val(),
                        detailDate: $tr.find('td:eq(9) input').val()
                    };
                    submitData.items.push(item);
                });
                
                // 模拟提交
                console.log('提交数据：', submitData);
                alert('提交成功');
                
                return false; // 阻止表单跳转
            });
            
            // 取消按钮
            $('#btnCancel').on('click', function() {
                if (confirm('确定要取消并清空表单吗？')) {
                    // 清空基础信息表单
                    $('input[name="planTitle"]').val('');
                    $('input[name="planNo"]').val('');
                    $('select[name="sourceType"]').val('');
                    $('input[name="salesOrder"]').val('');
                    $('input[name="planStartTime"]').val('');
                    $('input[name="planEndTime"]').val('');
                    $('input[name="requirementDate"]').val('');
                    $('select[name="status"]').val('');
                    $('textarea[name="remark"]').val('');
                    
                    // 清空物品表格
                    if ($('#itemTable tbody tr').length > 0 && $('#itemTable tbody tr:first td').attr('colspan') !== '11') {
                        $('#itemTable tbody').html('<tr><td colspan="11" style="text-align: center;">暂无数据，请点击添加按钮</td></tr>');
                    }
                    
                    // 重置总计
                    $('.total-count').text('总计：0');
                }
            });
            
            // 初始化总计显示
            calculateTotal();
        });
    </script>
}

